// @ts-nocheck
import prompt from '@system.prompt';
import request from '@system.request';
import geolocation from '@system.geolocation';
import fetch from '@system.fetch';
import file from '@ohos.file'
import fileio from '@ohos.fileio';
import ability_featureAbility from '@ohos.ability.featureAbility';



export default {
    data: {
        array6:['','','','','',''],
        array7:['','','','','','',''],
        datalist: [ {
                       title: '体重记录'
                   }],

        calendar: [{
                       data: '一'
                   }, {
                       data: '二'
                   }, {
                       data: '三'
                   }, {
                       data: '四'
                   }, {
                       data: '五'
                   }, {
                       data: '六'
                   }, {
                       data: '七'
                   }],

        calendarData: [{
                           data: '一'
                       }, {
                           data: '二'
                       }, {
                           data: '三'
                       }, {
                           data: '四'
                       }, {
                           data: '五'
                       }, {
                           data: '六'
                       }, {
                           data: '七'
                       },
                       {
                           data: '一'
                       }, {
                           data: '二'
                       }, {
                           data: '三'
                       }, {
                           data: '四'
                       }, {
                           data: '五'
                       }, {
                           data: '六'
                       }, {
                           data: '七'
                       },
                       {
                           data: '一'
                       }, {
                           data: '二'
                       }, {
                           data: '三'
                       }, {
                           data: '四'
                       }, {
                           data: '五'
                       }, {
                           data: '六'
                       }, {
                           data: '七'
                       },
                       {
                           data: '一'
                       }, {
                           data: '二'
                       }, {
                           data: '三'
                       }, {
                           data: '四'
                       }, {
                           data: '五'
                       }, {
                           data: '六'
                       }, {
                           data: '七'
                       },
                       {
                           data: '一'
                       }, {
                           data: '二'
                       }, {
                           data: '三'
                       }, {
                           data: '四'
                       }, {
                           data: '五'
                       }, {
                           data: '六'
                       }, {
                           data: '七'
                       },


        ],
        mouth: ['1', '2', '2', '2', '2', '2', '2'],

        array6:['','','','','',''],
        array7:['','','','','','',''],
        timeCopy:{},
        weekList: ['日', '一', '二', '三', '四', '五', '六'],
        res:[],
        allday:0,
        week:'',
        dayMark:'',

        aaa: ['', '', '', '', '', ''],
        bbb: ['', '', '', '', '', '', ''],
        dayAry: [],
        timeStr: '',
        res : [],
        latitude:'',
        longtitude:'',
        setClick:false,
        getCodeNum:false,
        initNum:5,
        countDown:false,
        userId:'',
        userName:'未登录',
        timeCopy:{},
        morning:'',
        morningStatus:'未完成',
        afternoon:'',
        afternoonStatus:'未完成',
        signTime_hours:'',
        signTime_minutes:'',
        tabsIndex:0
    },

    async onInit() {

        this.timeCopy = this.setData(new Date());
        console.log("时间aaa:"+JSON.stringify(this.timeCopy))
        this.res = await this.getCurrentMonthDays()
        console.log("shu组："+this.res)
        this.getLocation()
        // 工具方法 - end
    },
    change(e){
      console.info('tabs索引值：'+JSON.stringify(e))
        this.tabsIndex=e.index
        console.info(this.tabsIndex)
    },
    //签到查询
    clockQuery(){
        let that = this;
        let timeDay = new Date().getDate()
        let Http = 'http://120.78.198.170:3200/clockQuery?'+'userId='+this.userId+'&timeDay='+timeDay;
        console.log("签到查询地址："+Http)
        this.$app.$def.httpRequest(Http,
            (res)=>{
                console.info(JSON.stringify(res))
                console.info("签到查询信息：" + JSON.parse(res.data))
                console.info("签到查询信息：" + JSON.stringify(JSON.parse(res.data)))
                let resList = JSON.parse(res.data)
                for(let i = 0;i<resList.length;i++){
                    console.log("解析的list："+JSON.parse(resList[i].time).year)
                    if(JSON.parse(resList[i].time).month && JSON.parse(resList[i].time).day){
                        that.morningStatus = "已签到"
                        that.signTime_hours = JSON.parse(resList[i].time).hours
                        that.signTime_minutes = JSON.parse(resList[i].time).minutes
                    }

                }

            },
            (res)=>{
                //            console.log
                console.log("签到查询信息失败了",res)
            }
        )
    },

    async setImage(){
        console.log("点击图片")
        var action = {};
        // config.json中的bundleName值
        action.bundleName = "com.example.clockin";
        // config.json中abilities的name值
        action.abilityName = 'com.example.clockin.set_profileServiceAbility';
        // 标识，用于与前端操作类型匹配，类似MVC的接口路径
        action.messageCode = 1001;
        // 设置数据
        //        action.data = actionData;
        // 设置调用类型 ability 或 internal ability
        action.abilityType = 1;
        // 设置同步类型
        action.syncOption = 0;
        console.info("请求格式" + action);
        // 调用java pa
        console.info("运行开始")
        await FeatureAbility.callAbility(action);

        console.info("运行结束")
    },
    onShow(){
        this.getLocation()
        this.clockQuery()

        if(this.userId!=''){
            let Http = 'http://120.78.198.170:3200/registerQuery?'+'userId='+this.userId;
            console.log("请求地址uri:"+Http)
            fetch.fetch({
                //            url: Http+this.clockCode+"&"+clockTime+username,
                url: Http,
                responseType: 'json',
                headers: {
                    'content-type': 'application/json'
                },
                method: 'GET',
                success: res => {
                    console.info(res)
                    console.info("注册信息：" + res.data)
                    //                console.info("注册信息1："+res.data.success)
                    console.info("注册信息2："+JSON.parse(res.data).success)
                    console.info("注册信息3："+JSON.parse(res.data).data.lisdata.insertId)
                    if(JSON.parse(res.data).success){
                        this.userName= JSON.parse(res.data).data.lisdata.insertName
                        this.$element('simplepanel').close()
                    }
                    this.cancelSchedule()
                },
                fail: function() {
                    console.info("fetch fail");
                }
            });
        }

    },

    UploadFile(){
        request.upload({ url: 'http://**.**.**.**:***/*****',
            files:[{filename: this.picturename, name:'file',uri:'internal://cache/'+this.picturename,type:'png',
                   }]
        },
            (err, data) => {
                prompt.showToast({
                    message: JSON.stringify(data)
                })
                if (err) {
                    prompt.showToast({
                        message: JSON.stringify(err)
                    })
                    return;
                }
                var uploadTask = data;
            });
    },
    set(){
        this.setClick = !this.setClick;
        if(this.setClick){
            this.$element('simplepanel').show()

        }else{
            this.$element('simplepanel').close()

        }
    },
    sign(){
        var Http = "http://120.78.198.170:3200/sign?";
        let that = this;
        if(this.userId!=''){
            console.log("请求签到用户Id:"+this.userId)
            fetch.fetch({
                //            url: Http+this.clockCode+"&"+clockTime+username,
                url: Http+'locationMessage='+this.longtitude+"&userId="+this.userId,
                responseType: 'json',
                headers: {
                    'content-type': 'application/json'
                },
                method: 'GET',
                success: function(res) {
                    console.info(res)
                    console.info("我是pinglun列表：" +res.data)
                    let rest = JSON.parse(res.data)
                    console.log('签到请求时间：'+rest.data);
                    console.log('签到请求时间2：'+(rest.data).time);
                    console.log('签到请求值：'+rest.success);
                    if(rest.success){
                        console.log("成功")
                        that.signTime_hours = (rest.data).time.hours
                        that.$set('signTime_minutes',(rest.data).time.minutes)

                        console.log("时间打印："+that.signTime_hours+'@@@@'+that.signTime_minutes)
                        that.morningStatus='已签到'
                    }else{
                        console.log("失败")
                        //                    this.$element('simplepanel').show()
                    }
                    this.cancelSchedule()
                },
                fail: function() {
                    console.info("fetch fail");
                }
            });

        }else{
            that.setClick = !that.setClick;
            if(that.setClick){
                that.$element('simplepanel').show()

            }else{
                that.$element('simplepanel').close()

            }
        }
    },
    getCode(){
        let that = this;
//        that.initNum = 5
        that.countDown = !that.countDown

        let timer = setInterval(function(){
                let aa = that.initNum--;
                console.info('我是d'+ that.initNum)
                that.$set('initNum',that.initNum)
//                that.initNum = aa
                if(that.initNum == 0){
                    clearInterval(timer)
                    that.countDown = !that.countDown
                    this.getCodeNum = !this.getCodeNum
                    that.initNum = 5
                }
            },1000)

//        while(this.initNum!=0){
//        }
//        console.log("倒计时："+this.initNum)
//        if(this.initNum == 0)
//        clearInterval(init)


    },


    showPanel() {
        this.$element('simplepanel').show()
    },
    closePanel() {
        this.$element('simplepanel').close()
    },
    changeMode(e) {
        this.modeFlag = e.mode
    },

    onsubmit(result){
        console.log("姓名："+result.value.nikName)
        let nickName;
        nickName = result.value.nikName;
        console.log("性别："+result.value.sex)
        let sex
        sex = result.value.sex
        console.log("手机号"+result.value.phoneNum)
        let phoneNum = result.value.phoneNum
        console.log("验证码："+result.value.verificationCode)
//        let Http = 'http://120.78.198.170:3100/registerClock/?'+'nickName='+nickName+'&sex='+sex+'&phoneNum='+phoneNum;
        let Http = 'http://120.78.198.170:3200/register?'+'&phoneNum='+phoneNum;
        console.log("请求地址uri:"+Http)

//        getApp.httpRequest()

        this.$app.$def.httpRequest(Http,
            (res)=>{
            console.info(JSON.stringify(res))
            console.info("注册信息：" + JSON.parse(res.data))
            //                console.info("注册信息1："+res.data.success)
            console.info("注册信息2："+JSON.parse(res.data).success)
            console.info("注册信息3："+JSON.parse(res.data).userInfo)
            let aa = JSON.parse(res.data).userInfo
//            let bb = JSON.parse(aa).userid
            console.log("aa值为："+JSON.stringify(aa))
            console.log("bb值为："+aa.userid)

            //            let ida = JSON.parse(res.data).data
//            let idaa = JSON.parse(ida).userId
//            console.log("aaaa####:",idaa)

//            console.info("注册信息3："+JSON.parse(res.data).data.lisdata.insertId)
            if(JSON.parse(res.data).success){
                console.log("aa:"+aa)
                this.userId= aa.userid
                this.userName = aa.userName
                console.log("yong户id："+this.userId)
                this.$element('simplepanel').close()
            }
            this.cancelSchedule()
        },
        (res)=>{
//            console.log
            console.log("失败",res)
        }
        )

//        fetch.fetch({
//            url: Http,
//            responseType: 'json',
//            headers: {
//                'content-type': 'application/json'
//            },
//            method: 'GET',
//            success: res => {
//
//                console.info(res)
//                console.info("注册信息：" + res.data)
////                console.info("注册信息1："+res.data.success)
//                console.info("注册信息2："+JSON.parse(res.data).success)
//                console.info("注册信息3："+JSON.parse(res.data).data.lisdata.insertId)
//                if(JSON.parse(res.data).success){
//                    this.userId= JSON.parse(res.data).data.userId
//                    this.$element('simplepanel').close()
//                }
//                this.cancelSchedule()
//            },
//            fail: function() {
//                console.info("fetch fail");
//            }
//        });
    },
    onreset(){

    },

    getLocation() {
        let that = this
        geolocation.getLocation({
            success: function(data) {
                console.log('success get location data. latitude:' + data.latitude);
                that.latitude = data.latitude;
            },
            fail: function(data, code) {
                console.log('fail to get location. code:' + code + ', data:' + data);
            },
        });
    },
    //日历代码*******************************
    setData(time) {
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let day = time.getDate();
        return {year, month, day};
    },
    async handlChangeDate(flag, val) {
        this.timeCopy[flag] += val;
        console.log("点击上下按钮："+JSON.stringify(this.timeCopy))
        if (this.timeCopy.month > 12) {
            this.timeCopy.month = 1;
            this.timeCopy.year += 1;
        }
        if (this.timeCopy.month < 1) {
            this.timeCopy.month = 12;
            this.timeCopy.year -= 1;
        }
        this.res = await this.getCurrentMonthDays();
        const aa =this.$elememt('textShow')
        console.log('dom元素：'+aa)
        console.log('res结果数组：'+this.res)
    },
    async getCurrentMonthDays() {
        let {year, month} = this.timeCopy;
        let firstDay = new Date(`${year}-${month}-01`);
        console.log("输出第一天："+firstDay)
        console.log("输出第一天2："+firstDay.getDate())
        this.week = firstDay.getDay();
        console.log("输出星期几："+this.week)
        let beginDay;
        if (this.week === 0) {
            beginDay = firstDay - 7 * 1000 * 60 * 60 * 24;
        } else {
            beginDay = firstDay - this.week * 1000 * 60 * 60 * 24;
        }
        let dateArr = [];
        this.count();
        //查询当月签到数组
        let Httpa = 'http://120.78.198.170:3200/clockArray?'+'userId='+this.userId+'&month='+this.timeCopy.month;

        let ArrayListInfo
        await fetch.fetch({
            //            url: Http+this.clockCode+"&"+clockTime+username,
            url: Httpa,
            responseType: 'json',
            headers: {
                'content-type': 'application/json'
            },
            method: 'GET',
            success: res => {
                console.info(res)
                console.info("签到信息：" + res.data)
                let aaa = JSON.parse(res.data);
                if(aaa.length>0){
                    console.log('查询当月签到数组:'+aaa[0].clockArray);
                    ArrayListInfo = aaa[0].clockArray
                }else{
                    ArrayListInfo=''
                }


            },
            fail: function() {
                console.info("fetch fail");
            },
            complete:function(){
            }})
        //查询签到信息
        let signList
        signList = await this.querySign(beginDay);
        console.log('签到数组bbb：'+signList)
        console.log('签到数组ccc：')
        let flag = -1;
        let bbb =ArrayListInfo.split(",")

        for (let i = 0; i < 42; i++) {
//            bbb = signList[0].clockArray
//            console.log('进入42循环'+JSON.parse(signList));
//            console.log('进入42aa循环'+JSON.parse(bbb[1].time));
            let date = new Date(beginDay + i * 1000 * 60 * 60 * 24).getDate();
            console.log('42循环'+date+'####'+bbb)
            if(date == 1 && flag == -1){
                flag = 1
            }


            dateArr.push({
                date:date,
                classa:flag==1? "text-a":"text-b"
            });

            if(bbb.length>0 && flag == 1){
                for(let j = 0;j<bbb.length;j++) {
                    console.log('进入循环a')
                    //                    let date_a = JSON.parse(bbb[j].time)
                    //                    let date_a = bbb[j]
                    console.log('循环a里边的signList列表aa：' + bbb[j]);
                    console.log('循环a里边的signList列表：' + bbb[j]+'@@@'+date);
                    console.log(typeof bbb[j]+'@@@'+typeof date)
                    console.log('循环a里边:'+ (date==bbb[j]))
                    if(date==bbb[j] && flag==1){
                        dateArr[i].status='已签到';
//                        dateArr[i].date=date;
//                        dateArr[i].classa = flag==1? "text-a":"text-b"
                        break;
                    }else{
//                        dateArr[i].status='未签到';
//                        dateArr[i].date=date;
//                        dateArr[i].classa = flag==1? "text-a":"text-b"
                    }
                }
            }
            else{
//                dateArr[i].status= flag==1? '未签到':''
//                dateArr[i].date=date;
//                dateArr[i].classa = flag==1? "text-a":"text-b"
            }

            if(date == this.allday && flag ==1){
                flag = -2
            }
        }

        console.log("输出数组：")
        console.log("输出数组："+JSON.stringify(dateArr))
        return dateArr;

    },
    count(){

        if (this.timeCopy.month!=2) {
            if(this.timeCopy.month==4||this.timeCopy.month==6||this.timeCopy.month==9||this.timeCopy.month==11){
                this.allday = 30;
            }else{
                this.allday=31;
            }
        }else{
            if ((this.timeCopy.year%4==0&this.timeCopy.year%100!=0)||(this.timeCopy.year%400==0)) {
                this.allday=29;
            }else{
                this.allday=28
            }
        }
    },
//    formatterTime() {
//        let {year, month, day} = this.timeCopy;
//        return `${year}-${month}-${day}`;
//    },

    httpReq(){
        fetch.fetch({
            url: 'http://120.78.198.170:3200/getVerificationCode',
            success: function(response) {
                console.info("fetch success");
                that.responseData = JSON.stringify(response);
            },
            fail: function() {
                console.info("fetch fail");
            }
        });
    },


    //查询用户签到信息  http://120.78.198.170:3200/clockInfoQuery?userId=1
    async querySign(beginDay){

        let signLists = []

        let Http = 'http://120.78.198.170:3200/clockQueryCandle?'+'userId='+this.userId+'&month='+this.timeCopy.month;
        console.log("请求地址uri:"+Http)
        let aaa = await fetch.fetch({
            //            url: Http+this.clockCode+"&"+clockTime+username,
            url: Http,
            responseType: 'json',
            headers: {
                'content-type': 'application/json'
            },
            method: 'GET',
            success: res => {
                console.info(res)
                console.info("签到信息：" + res.data)
                signLists=res.data;
                let dateArr = [];
                 console.log('签到信息列表aaa:'+signLists);
                //        //        for(let i = 0; i<this.allday;i++){
                //        //            dateArr.push(new Date(beginDay + i * 1000 * 60 * 60 * 24).getDate());
                //        //
                //        //        }
                //        //记录每月1号第一次出现的位置
//                        let flag = -1;
//                        for (let i = 0; i < 42; i++) {
//                            //            let dayObj = {}
//                            //            dateArr.push(new Date(beginDay + i * 1000 * 60 * 60 * 24).getDate());
//
//                            let date = new Date(beginDay + i * 1000 * 60 * 60 * 24).getDate();
//                            if(date == 1 && flag == -1){
//                                flag = 1
//                            }
//                            dateArr.push({
//                                date:date,
//                                classa:flag==1? "text-a":"text-b"
//                            }
//                            );
//                            if(date == this.allday && flag ==1){
//                                flag = -2
//                            }
//                        }
//                        console.log("输出数组："+JSON.stringify(dateArr))
//                        return dateArr;
            },
            fail: function() {
                console.info("fetch fail");
            },
            complete:function(){
            }
        });
        console.log('aaa是:'+JSON.stringify(aaa))
        console.log('返回签到列表signLists:'+signLists)
        return signLists;
    }

}